<template>
	<view class="content">
		<scroll-view 
		class="chat-wrap"
		scroll-y
		:scroll-with-animation="showAnimation"
		:style="{'height': scrollHeight + 'px','padding-top': scrollViewTop + 'px','box-sizing': 'border-box'}"
		@scrolltoupper="scrolltoupper"
		:scroll-into-view="scrollIntoId">
			<view class="chat-main" :style="{'margin-bottom': bottom + 'px'}">
				<block v-for="(item, index) in messages.messageList" :key="index">
					<view class="chat-ls" >
						<view class="chat-time" v-if="item.showTime">{{item.showTime | filterTime}}</view>
						<view class="msg-m" :class="item.uid == user.uid ? 'msg-right':'msg-left'">
							<view>
								<image class="user-avatar" :src="item.avatar"></image>
							</view>
							<view class="messages" >
								<view v-if="item.contentType == 1" class="message-text">
									<text selectable space>{{item.contentText}}</text>
								</view>
								<image v-if="item.contentType == 2" 
								class="msg-img" 
								:src="item.imgUrl" 
								:data-img-url="item.imgUrl"
								@click="previewImage"
								mode="widthFix"></image>
								<audio class="chat-voice" v-if="item.contentType == 3" :src="item.voiceUrl"></audio>
							</view>
						</view>
					</view>
					<view v-if="item" :id="'msg_' + item.id"></view>
					
				</block>
			</view>
			<view id="msg_bottom"></view>
			
		</scroll-view>
		<chat-input 
		@clickSend="sendMessage" 
		@inputOnFocus="inputOnFocus" 
		@inputBlur="inputBlur"
		@input="input"
		:value="inputValue"
		@linechange="linechange"
		@clickTuPian="clickTuPian"
		@clickXiangJi="clickXiangJi"
		@clickJiaHao="clickJiaHao"
		@clickBiaoQing="clickBiaoQing"
		@clickYuYin="clickYuYin"
		></chat-input>
		<view class="emoji" v-if="showEmoji">
			<block v-for="(item,index) in emoji">
				<view class="emoji-item">{{item}}</view>
			</block>
		</view>
		<mpopup ref="mpopup" :isdistance="true"></mpopup>  
	</view>
</template>

<script>
	import chatInput from '@/components/chatInput/chatInput.vue';
	import {utils} from '@/utils/utils.js';
	import {SocketChat} from '@/model/socketChat.js';
	import {Friend} from '@/model/friend.js';
	import {Message} from '@/model/message.js';
	import {UploadFile} from '@/model/uploadFile.js';
	// 模拟请求数据
	import Datas from '@/datas/getDatas.js';
	
	import mpopup from '@/components/xuan-popup/xuan-popup.vue'
	export default {
		data() {
			return {
				messages:[],
				oldTime: new Date(),
				scrollIntoId:'',
				scrollHeight:500,
				bottom: 90,
				oldBottom: 0,
				showAnimation:false,
				inputValue:'',
				scrollViewTop:0,
				socketTask:null,
				user:{},
				friend:null,
				msgIndex:0,
				friendUid:'',
				isRefreshMsg: false,
				messagePage:1,
				emoji:[],
				showEmoji:false
			}
		},
		components:{
			chatInput,
			mpopup
		},
		created() {
			let res = uni.getSystemInfoSync()
			this.scrollHeight = res.windowHeight
					
		},
		mounted() {
			let view = uni.createSelectorQuery().in(this).select(".chat-input");
			// view.boundingClientRect(data => {
			// }).exec();
		},
		onBackPress() {
			let msgIndex = this.$store.chatList.findIndex(item => item.uid == this.friendUid)
			this.$store.chatList[msgIndex].tip = 0;
			this.$store.chatList[msgIndex].messageList.forEach(item=>item.messageStatus = 1)
		},
		onLoad(option) {
			console.log(this.$store.user)
			let res = uni.getSystemInfoSync()
			this.scrollHeight = res.windowHeight
			this.emoji = Datas.getEmoji
			this.$store.socketTask.set_uni(this)
			this.user = this.$store.user
			this.bottom = uni.upx2px(190)
			this.oldBottom = uni.upx2px(190)
			this.socketTask = this.$store.socketTask
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('acceptDataFromOpenerPage', async (data)=> {
				this.friendUid = data.friendUid
				if(!this.$store.friendsMsgFlag[this.friendUid]){
					this.isRefreshMsg = true;
				}
				let res = await Friend.getFriendInfo({friendId:this.friendUid})
				this.friend = res.data
				this.msgIndex = this.$store.chatList.findIndex(item=>item.uid == this.friendUid)
				if(this.msgIndex == -1){
					let msgObj = {
						toFriendId: this.user.uid,
						friendName: this.friend.friendName,
						avatar: this.friend.avatarUrl,
						uid: this.friendUid,
						messageList:[]
					}
					this.$store.chatList.push(msgObj)
					this.$utils.setStorage("chatList",this.$store.chatList)
					this.msgIndex = this.$store.chatList.findIndex(item=>item.uid == this.friendUid)
					console.log(this.msgIndex)
				}
				console.log(this.$utils.getStorage("chatList"))
				this.$store.chatList =this.$utils.getStorage("chatList")
				this.messages = this.$store.chatList[this.msgIndex]
				this.messages.messageList = this.messageArray();
				uni.setNavigationBarTitle({
				    title:this.messages.friendName
				});
				
				// if(this.isRefreshMsg){
				// 	let msg = await Message.getMessage({friendUid:this.friendUid})
				// 	if(data.isSearch){
				// 		if(msg.data.data[0]){
				// 			let chatObj = {
				// 				toFriendId: msg.data.data[0].toFriendId,
				// 				friendName: this.friend.friendName,
				// 				avatar: msg.data.data[0].avatar,
				// 				uid: msg.data.data[0].uid,
				// 				messageList:[]
				// 			}
				// 			this.msgIndex = 0
				// 			this.$store.chatList.unshift(chatObj)
				// 		}
				// 	}
				// 	if(this.msgIndex != -1){
				// 		this.$store.chatList[this.msgIndex].messageList = msg.data.data;
				// 		this.$utils.setStorage("chatList",JSON.stringify(this.$store.chatList))
				// 		this.$store.friendsMsgFlag[this.friendUid] = true
				// 	}
				// }else{
					// this.$store.chatList = JSON.parse(this.$utils.getStorage("chatList"))
				// }
				
				// this.messages = this.$store.chatList[this.msgIndex]
				// this.messages.messageList = this.messageArray();
				this.$nextTick(e=>{
					this.scrollIntoId = 'msg_' + this.messages.messageList[this.messages.messageList.length - 1].id
					// this.scrollIntoId = 'msg_bottom'
				})
			})
			
		},
		filters:{
			filterTime(sendTime){
				return utils.dateTime(sendTime);
			}
		},
		computed:{
		},
		methods: {
			messageArray(){
				return this.messages.messageList.map((item,index)=>{
					let t = utils.spaceTime(this.oldTime, item.sendTime)
					if(t)
						this.oldTime = item.sendTime
					item.showTime = t 
					if(index == 0){
						let idate = new Date(item.sendTime)
						item.showTime = idate.getTime()
					}
					return item;
				})
			},
			input(value){
				this.inputValue = value
				
			},
			linechange(e){
				if(e.height > 120)
					return
				this.bottom = this.oldBottom + e.height
				this.scrollIntoId = 'msg_bottom'
			},
			clickTuPian(){
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album"], //从相册选择
					success: async (res) => {
						uni.showLoading({
							title:"发送中"
						})
						let r = await UploadFile.uploadFiles([{
								name:'files',
								uri:res.tempFilePaths[0]
							}]
						)
						this.showAnimation = true
						let message = {
							uid:this.$store.user.uid,
							avatar:this.$store.user.avatarUrl,
							toFriendId:this.friend.uid,
							contentText:this.inputValue,
							contentType:2,
							messageStatus:2,
							voiceUrl:'',
							imgUrl:r.data.map(item=>{return item.fileUrl})[0]
						}
						this.inputValue = ''
						this.socketTask.sockSend(message)
					},
				});
			},
			clickXiangJi(){
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["camera"], //从相机拍照
					success: async (res) => {
						uni.showLoading({
							title:"发送中"
						})
						let r = await UploadFile.uploadFiles([{
								name:'files',
								uri:res.tempFilePaths[0]
							}]
						)
						this.showAnimation = true
						let message = {
							uid:this.$store.user.uid,
							avatar:this.$store.user.avatarUrl,
							toFriendId:this.friend.uid,
							contentText:this.inputValue,
							contentType:2,
							messageStatus:2,
							voiceUrl:'',
							imgUrl:r.data.map(item=>{return item.fileUrl})[0]
						}
						this.inputValue = ''
						this.socketTask.sockSend(message)
					},
				});
			},
			clickJiaHao(){
				this.$refs.mpopup.open({
					type:'warn',
					content:'暂未开放',
					timeout:1000,
					isClick:false
				});
			},
			clickBiaoQing(){
				this.$refs.mpopup.open({
					type:'warn',
					content:'暂未开放',
					timeout:1000,
					isClick:false
				});
			},
			clickYuYin(){
				this.$refs.mpopup.open({
					type:'warn',
					content:'暂未开放',
					timeout:1000,
					isClick:false
				});
			},
			sendMessage(){
				if(this.inputValue == '' || !this.inputValue){
					return
				}
				this.showAnimation = true
				let message = {
					uid:this.$store.user.uid,
					avatar:this.$store.user.avatarUrl,
					toFriendId:this.friend.uid,
					contentText:this.inputValue,
					contentType:1,
					messageStatus:2,
					voiceUrl:'',
					imgUrl:''
				}
				this.inputValue = ''
				this.socketTask.sockSend(message)
			},
			inputOnFocus(e){
				this.scrollViewTop = e.detail.height - uni.upx2px(100)
				this.bottom = uni.upx2px(260)
				this.$nextTick(e =>{
					this.scrollIntoId = 'msg_' + this.messages.messageList[this.messages.messageList.length - 1].id
					this.scrollIntoId = 'msg_bottom'
				})
			},
			inputBlur(){
				this.bottom = uni.upx2px(180)
				this.scrollViewTop = 0
			},
			imgList(){
				return this.messages.filter(item => item.img_url != '').map(item => item.img_url)
			},
			scrollToBottom(){
				this.$nextTick(e=>{
					this.scrollIntoId = 'msg_' + this.messages.messageList[this.messages.messageList.length - 1].id
					// this.scrollIntoId = 'msg_bottom'
				})
			},
			scrolltoupper(){
				console.log(this.friend.uid)
			},
			previewImage(e){
				uni.previewImage({
				   urls: this.imgList(),
				   current:e.target.dataset.imgUrl,
				   longPressActions: {
					   itemList: ['发送给朋友', '保存图片', '收藏'],
					   success: function(data) {
						   console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
					   },
					   fail: function(err) {
						   console.log(err.errMsg);
					   }
				   }
			   });
			},
			
		}
	}
</script>

<style>
	page{
		height: 100%;
		background-color: #f2f2f2;
	}
</style>
<style lang="scss" scoped>

	.content{
		.nav-bar-title{
			width: 100%;
			.nick-name-title{
				text-align: center;
			}
		}
	}
	.emoji{
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		background-color: #FFF;
		.emoji-item{
			margin: 10rpx 20rpx;
		}
	}
	.chat-wrap{
		// height: 100%;
		box-sizing: border-box;
		.chat-main{
			padding: 0 10rpx;
			.chat-ls{
				.chat-time{
					text-align: center;
					height: 28rpx;
					font-size: 24rpx;
					font-weight: 400;
					color: #888888;
					padding: 20rpx 0;
				}
				.msg-m{
					display: flex;
					padding: 10rpx 0;
					line-height: 1.2;
					overflow: hidden;
					.user-avatar{
						height: 80rpx;
						width: 80rpx;
						border-radius: 100%;
					}
					
					.messages{
						margin-top: 10rpx;
						padding: 15rpx;
						font-size: 24rpx;
						box-sizing: border-box;
						max-width: 450rpx;
						border-radius: 10rpx;
						position: relative;
						word-break:break-all;
						.message-text{
							line-height: 1.2;
							padding: 0;
						}
						.msg-img{
							max-width: 420rpx;
							border-radius: 10rpx;
						}
						.chat-voice{
							max-width: 400rpx;
						}
					}
				}
				.msg-left{
					.messages{
						margin-left: 30rpx;
						background-color: #FFFFFF;
						&::before{
							position: absolute;
							top: 10rpx;
							left: -28rpx;
							display: inline-block;
							content: '';
							border-right: 14rpx #FFFFFF solid;
							border-top: 14rpx transparent  solid;
							border-left: 14rpx transparent solid;
							border-bottom: 14rpx transparent solid;
						}
					}
				}
				.msg-right{
					flex-direction: row-reverse;
					.messages{
						margin-right: 30rpx;
						background-color: $fun-theme-color;
						&::before{
							position: absolute;
							top: 10rpx;
							right: -28rpx;
							display: inline-block;
							content: '';
							border-right: 14rpx transparent solid;
							border-top: 14rpx transparent  solid;
							border-left: 14rpx $fun-theme-color solid;
							border-bottom: 14rpx transparent solid;
						}
					}
				}
			}
		}
	}
</style>
